import java.io.*;

import lejos.nxt.remote.NXTComm;
import lejos.pc.comm.NXTConnector;



public class PCBluetooth extends Thread 
{
	private DataMessageListener _listener = null;
	private NXTConnector _connector = null;
	private DataInputStream _inStream = null;
	private DataOutputStream _outStream = null;
	
	private boolean _connected = false;
	private String _deviceURL = null;
	
	public PCBluetooth(String deviceURL, DataMessageListener listener)
	{
		_deviceURL = deviceURL;
		_listener = listener;
		_connector = new NXTConnector();
		
		setDaemon(true);
		start();
	}

	public synchronized String getDeviceURL()
	{
		return _deviceURL;
	}
	
	private boolean enforceConnection()
	{

		if (!_connected) 
		{
			_connected = _connector.connectTo(_deviceURL);
			
			if( _connected )
			{
				_inStream = _connector.getDataIn();
				_outStream = _connector.getDataOut();
			}

		}
		return _connected;
	}	
	
	public synchronized void sendMessage(DataMessage message)
	{
		if(_connected)
		{
			try 
			{
				_outStream.write(message.getBytes(), 0, message.getSize());
				_outStream.flush();
			} 
			catch (IOException e) {
				System.out.println(e);
			}
		}
	}
	
	
	public void run()
	{
		DataMessage message = null;
		
		while (true)
		{
			// Ensure connection
			enforceConnection();
			
			
			synchronized(this)
			{
				if( _connected)
				{
					
					try 
					{
						byte b0 = _inStream.readByte();
						byte b1 = _inStream.readByte();
						
						byte[] data = new byte[b1 + 2];
						for(int i = 0 ;i < b1 ; i++ )
						{
							data[i+2] = _inStream.readByte();
						}
						data[0] = b0;
						data[1] = b1;
							
						message = new DataMessage(data); 
						
					}
					catch (IOException e) 
					{
						System.out.println(e);
						_connected = false;
					}
				}
			}
			
			if( message != null && message.isValid() && _listener != null)
			{
				_listener.messageReceived(this, message);
				message = null;
			}
							
				
			// Relax (Allow to send)
			try 
			{
				Thread.sleep(100);
			} 
			catch (InterruptedException e) 
			{
				System.out.println(e);
			}
			
			
		}
		
	}
	
}
